// src/stores/authStore.js
import { defineStore } from 'pinia';
import { router } from '../router';
import { userMenuList, adminMenuList } from '../mock/authData';

export const useAuthStore = defineStore('auth', {
    state: () => ({
        currentUser: null,
        token: '',
        loginMethod: '',
        menuList: [],
        hasLoadedDynamicRoutes: false
    }),
    actions: {
        async login(credentials, method) {
            try {
                const mockUser = {
                    username: credentials.username,
                    isAdmin: credentials.username === 'admin'
                };
                const mockToken = 'mock_token';
                this.currentUser = mockUser;
                this.token = mockToken;
                this.loginMethod = method;
                localStorage.setItem('auth_token', this.token);
                localStorage.setItem('current_user', JSON.stringify(this.currentUser));

                // 根据用户角色设置菜单
                this.menuList = mockUser.isAdmin ? adminMenuList : userMenuList;

                // 使用 replace 替换当前路径，防止“前进/后退”回到登录页
                router.replace('/home');

                return { user: mockUser, token: mockToken };
            } catch (error) {
                console.error('登录出错:', error);
                throw error;
            }
        },
        logout() {
            this.currentUser = null;
            this.token = '';
            this.menuList = [];
            this.hasLoadedDynamicRoutes = false;
            localStorage.removeItem('auth_token');
            localStorage.removeItem('current_user');

            // 同样使用 replace 防止“后退”回原页面
            router.replace('/login');
        },
        async registerLawyer(data, licenseFile) {
            try {
                const mockResult = { success: true };
                if (mockResult.success) {
                    this.login({
                        phone: data.phone,
                        password: data.password
                    }, 'password');
                }
                return mockResult;
            } catch (error) {
                console.error('律师注册出错:', error);
                throw error;
            }
        },
        async register(data) {
            try {
                const mockResult = { success: true };
                if (mockResult.success) {
                    this.currentUser = data;
                    localStorage.setItem('current_user', JSON.stringify(this.currentUser));
                }
                return mockResult.success;
            } catch (error) {
                console.error('注册出错:', error);
                throw error;
            }
        },
        init() {
            const token = localStorage.getItem('auth_token');
            const user = JSON.parse(localStorage.getItem('current_user'));
            if (token && user) {
                this.token = token;
                this.currentUser = user;
                this.menuList = user.isAdmin ? adminMenuList : userMenuList;
            }
        }
    },
    getters: {
        isLoggedIn(state) {
            return !!state.currentUser;
        },
        isLawyer(state) {
            return state.currentUser?.type === 'lawyer';
        },
        userAvatar(state) {
            return state.currentUser?.avatar || '/default-avatar.png';
        }
    },
    persist: true
});